package rabbitmq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class ProducerDemo {
    public static void main(String[] args) throws IOException, TimeoutException {
        //1. 建立连接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("43.138.188.168");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("study");
        connectionFactory.setPassword("study");
        connectionFactory.setVirtualHost("study");
        Connection connection = connectionFactory.newConnection();
        //2. 开启信道
        Channel channel = connection.createChannel();
        //3. 声明交换机，目前使用内置的

        //4. 声明队列
        /**
         *  queueDeclare(String queue, boolean durable, boolean exclusive,
         *              boolean autoDelete, Map<String, Object> arguments) throws IOException {
         *
         * queue：队列名称
         * durable：可持久化
         * exclisive：是否独占
         * autoDelete：是否自动删除
         * arguments：参数，高级特性会用到
         *
         *  */
        channel.queueDeclare("demo1",true,false,false,null);
        //5. 发送消息
        /**
         * basicPublish(String exchange, String routingKey,
         *              AMQP.BasicProperties props, byte[] body)
         *    exchange：交换机名称
         *    routingKey：内置交换机，需要和接受消息的queue名称一致
         *    props：属性配置
         *    body：消息
         */
        for (int i = 0;i < 100;i++) {
            String msg = "hello demo" + i + "!";
            channel.basicPublish("","demo1",null,msg.getBytes());
            System.out.println("消息" + i + "发生成功！！！");
        }
        //6. 资源释放
        channel.close();
        connection.close();
    }
}
